package me.yuzho.study.javaweb;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** 创建线程来响应WEB请求
 * @author yzhou-citrix
 *
 */
public class ThreadWeb {
    
    private static final Logger log = LoggerFactory.getLogger(ThreadWeb.class);
    
    final static String response =
            "HTTP/1.0 200 OK\r\n" +
            "Content-type: text/plain\r\n" +
            "\r\n" +
            "Hello World\r\n";
    
    public static void handleRequest(Socket socket) throws IOException {
        // Read the input stream, and return "200 OK"
        try {
          BufferedReader in = new BufferedReader(
            new InputStreamReader(socket.getInputStream()));
          log.info(in.readLine());
          log.info("Handle request in thread: " + Thread.currentThread().getName());
          OutputStream out = socket.getOutputStream();
          out.write(response.getBytes(StandardCharsets.UTF_8));
        } finally {
          socket.close();
        }
    }
    
    public static class HandleRequestRunnable implements Runnable {
        
        final Socket socket;
        public HandleRequestRunnable(Socket socket) {
            this.socket = socket;
        }
        
        public void run() {
            try {
                handleRequest(socket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        
        ServerSocket listener = null;
        try {
            listener = new ServerSocket(8080);
            log.info("Server started.");
            
            while (true) {
                Socket socket = listener.accept();
                new Thread(new HandleRequestRunnable(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(listener != null) {
                try {
                    listener.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
